package com.jch.har.client;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoop;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

// 客户端ChannelFuture监听器：用于断线重连
public class ClientChannelFutureListener implements ChannelFutureListener {

    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");

    @Override
    public void operationComplete(ChannelFuture future) throws Exception {
        if (future.isSuccess()) {
            System.out.println(dateFormat.format(new Date()) + " netty client start done.");
            return;
        }
        System.err.println(dateFormat.format(new Date()) + " ClientChannelFutureListener 发现客户端失去服务器连接.");
        final EventLoop loop = future.channel().eventLoop();
        loop.schedule(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println(dateFormat.format(new Date()) + " ClientChannelFutureListener 开始执行重连操作.");
                    new NettyClient().connect("127.0.0.1", 1130);
                    System.out.println(dateFormat.format(new Date()) + " netty client start done.");
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    System.err.println(dateFormat.format(new Date()) + " netty client start error go reconnect...");
                }
            }
        }, 1L, TimeUnit.SECONDS);
    }
}
